
var selectedElement;
var view = { name:"New View", selectionFormula:""};

function setup(){
	//Setup properties tabs
	$( "#toolbox" ).tabs({show:true});
	initialiseDesigner();
	
	//Make the column add able to drag onto view
	$("#viewColumnAdder").draggable({
		helper:"clone",
		connectToSortable:"#viewContainer"
	});
	
	$("#viewContainer .viewColumn").click(function(){
		select(this);
	})
	
}


function initialiseDesigner(){
	$("#viewContainer").sortable({
		placeholder: "sortable-placeholder",
		verticle:false,
		receive: function( event, ui ) {
			var x = $(this).data().uiSortable.currentItem;
			var p = x.find(".columnContent");
			x.empty().append(p.children());
			x.attr("class","viewColumn");
			x.css("display","");
			//Assign a random id
			x.attr("id","c" + Math.floor(Math.random()*100000)); 
			x.click(function(){
				select(this);
			})
		}	
	}).disableSelection();
	
	//Setup Delete form element button
	$("#view_column_controls #delete").click(function(){
		$(currentElement).fadeOut('slow', function(){
			//Get the controls so we dont loose them !
			$("#viewContainer").append($("#view_column_controls").detach());
			$("#view_column_controls").addClass("hide");
			$(currentElement).remove();
		});
		
	})

	
	//Load View properties
	$("#viewPropertyName").val(view.name);
	$("#viewPropertySelectionFormula").val(view.selectionFormula);
	
}


function unSelectAll(){
	currentElement = null;
	$("#viewContainer .viewColumn").each(function(){
		$(this).removeClass("current")

	});
}

function select(element){
	unSelectAll();
	currentElement = element;
	$(element).addClass("current");
	//Add the tools
	var controls = $("#view_column_controls").detach();
	$(element).append(controls);
	controls.removeClass("hide");
	
	$("#columnPropertyID").val(currentElement.id);
	$("#columnPropertyHeader").val($(currentElement).find(".header").text());
	$("#columnPropertyFormula").val($(currentElement).find(".content").text());
}


function updateColumnProperties(){
	$(currentElement).find(".header").text($("#columnPropertyHeader").val());
	$(currentElement).find(".content").text($("#columnPropertyFormula").val());
}


function updateViewProperties(){
	view.name = $("#viewPropertyName").val();
	view.selectionFormula = $("#viewPropertySelectionFormula").val();
}


